package gdufs.lkl.calculator;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 历史记录查看Activity
 */
public class HistoryActivity extends AppCompatActivity {
    
    private static final String TAG = "HistoryActivity";
    public static final String EXTRA_SELECTED_EXPRESSION = "selected_expression";
    public static final String EXTRA_SELECTED_RESULT = "selected_result";
    private ListView listViewHistory;
    private LinearLayout emptyLayout;
    private CalculationHistory calculationHistory;
    private ArrayAdapter<String> historyAdapter;
    private List<CalculationHistory.HistoryEntry> historyEntries;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        
        // 设置工具栏
        setSupportActionBar(findViewById(R.id.toolbar));
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("计算历史");
        }
          // 初始化UI
        listViewHistory = findViewById(R.id.listViewHistory);
        emptyLayout = findViewById(R.id.emptyLayout);
        
        // 初始化历史记录管理器
        calculationHistory = CalculationHistory.getInstance(this);
        
        // 设置清空按钮点击监听
        findViewById(R.id.fab_clear_history).setOnClickListener(v -> showClearAllDialog());
        
        // 设置列表项点击监听
        listViewHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showHistoryItemDialog(position);
            }
        });
        
        // 设置长按删除
        listViewHistory.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showDeleteConfirmDialog(position);
                return true;
            }
        });
        
        loadHistoryData();
    }
      @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
      @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        
        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_switch_to_calculator) {
            // 切换到基础计算器
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_switch_to_scientific) {
            // 切换到科学计算器
            Intent intent = new Intent(this, ScientificCalculatorActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_switch_to_converter) {
            // 切换到换算器
            Intent intent = new Intent(this, ConverterActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_custom_function) {
            // 切换到自定义函数管理器
            Intent intent = new Intent(this, CustomFunctionManagerActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_history) {
            // 已经在历史记录界面，无需操作
            return true;
        } else if (id == R.id.action_settings) {
            // 切换到设置
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * 加载历史记录数据
     */
    private void loadHistoryData() {
        historyEntries = calculationHistory.getHistory();
          if (historyEntries.isEmpty()) {
            listViewHistory.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.VISIBLE);
        } else {
            listViewHistory.setVisibility(View.VISIBLE);
            emptyLayout.setVisibility(View.GONE);
            
            // 反转列表，最新的记录显示在最上面
            Collections.reverse(historyEntries);
            
            // 创建显示数据
            List<String> displayList = new ArrayList<>();
            for (CalculationHistory.HistoryEntry entry : historyEntries) {
                String displayText = entry.toString() + "\n" + 
                                   entry.timestamp + " (" + 
                                   (entry.calculatorType.equals("scientific") ? "科学" : "基础") + ")";
                displayList.add(displayText);
            }
            
            historyAdapter = new ArrayAdapter<>(this, 
                android.R.layout.simple_list_item_2, 
                android.R.id.text1, 
                displayList);
            listViewHistory.setAdapter(historyAdapter);
        }
    }
      /**
     * 显示历史记录项详情对话框
     */
    private void showHistoryItemDialog(int position) {
        if (position < 0 || position >= historyEntries.size()) {
            return;
        }
        
        CalculationHistory.HistoryEntry entry = historyEntries.get(position);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("计算记录详情");
        
        String calculatorName = entry.calculatorType.equals("scientific") ? "科学计算器" : "基础计算器";
        String message = "表达式: " + entry.expression + "\n\n" +
                        "结果: " + entry.result + "\n\n" +
                        "时间: " + entry.timestamp + "\n\n" +
                        "计算器: " + calculatorName;
        builder.setMessage(message);
        
        // 取消按钮 (左侧)
        builder.setNeutralButton("取消", null);
        
        // 复用表达式到对应计算器 (中间)
        builder.setNegativeButton("复用表达式", (dialog, which) -> {
            reuseToTargetCalculator(entry.expression, null, entry.calculatorType);
        });
        
        // 复用结果到对应计算器 (右侧)
        builder.setPositiveButton("复用结果", (dialog, which) -> {
            reuseToTargetCalculator(null, entry.result, entry.calculatorType);
        });
        
        builder.show();
    }
    
    /**
     * 复用到目标计算器
     * @param expression 要复用的表达式（可为null）
     * @param result 要复用的结果（可为null）
     * @param calculatorType 目标计算器类型
     */
    private void reuseToTargetCalculator(String expression, String result, String calculatorType) {
        Intent intent;
        
        // 根据计算器类型创建对应的Intent
        if ("scientific".equals(calculatorType)) {
            intent = new Intent(this, ScientificCalculatorActivity.class);
        } else {
            intent = new Intent(this, MainActivity.class);
        }
        
        // 添加要复用的数据
        if (expression != null) {
            intent.putExtra(EXTRA_SELECTED_EXPRESSION, expression);
        }
        if (result != null) {
            intent.putExtra(EXTRA_SELECTED_RESULT, result);
        }
        
        // 清除Activity栈，确保跳转到目标计算器
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        
        startActivity(intent);
        finish();
    }
    
    /**
     * 显示删除确认对话框
     */
    private void showDeleteConfirmDialog(int position) {
        if (position < 0 || position >= historyEntries.size()) {
            return;
        }
        
        CalculationHistory.HistoryEntry entry = historyEntries.get(position);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("删除记录");
        builder.setMessage("确定要删除这条计算记录吗？\n\n" + entry.toString());
        
        builder.setPositiveButton("删除", (dialog, which) -> {
            // 注意：historyEntries是反转的，需要计算原始索引
            int originalIndex = calculationHistory.getHistoryCount() - 1 - position;
            calculationHistory.removeHistory(originalIndex);
            loadHistoryData();
            Toast.makeText(this, "记录已删除", Toast.LENGTH_SHORT).show();
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    
    /**
     * 显示清空所有历史记录确认对话框
     */
    private void showClearAllDialog() {
        if (!calculationHistory.hasHistory()) {
            Toast.makeText(this, "暂无历史记录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("清空历史记录");
        builder.setMessage("确定要清空所有计算历史记录吗？此操作不可撤销。");
        
        builder.setPositiveButton("清空", (dialog, which) -> {
            calculationHistory.clearHistory();
            loadHistoryData();
            Toast.makeText(this, "历史记录已清空", Toast.LENGTH_SHORT).show();
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
}
